package com.zzzzzz.sys.dict;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import com.zzzzzz.plugins.shiro.I;

@Service
public class DictService {
	@Resource
	public DictDao dictDao;

	@Transactional
	public int save(Dict dict, I i) {
		dict.setUpdDt(new Date());
		dict.setUpdBy(i.getId());
		if (dict.getId() == null) {
			dict.setAddDt(new Date());
			dict.setAddBy(i.getId());
			dictDao.add(dict);
		} else {
			dictDao.updById(dict);
		}

		return 1;
	}

	public String getLb(String val, String cd, String defaultVal) {
		if (StringUtils.isNotBlank(cd) && StringUtils.isNotBlank(val)) {
			for (Dict dict : getDictListByCd(cd)) {
				if (cd.equals(dict.getCd()) && val.equals(dict.getVal())) {
					return dict.getLb();
				}
			}
		}
		return defaultVal;
	}

	public String getVal(String lb, String cd, String defaultLb) {
		if (StringUtils.isNotBlank(cd) && StringUtils.isNotBlank(lb)) {
			for (Dict dict : getDictListByCd(cd)) {
				if (cd.equals(dict.getCd()) && lb.equals(dict.getLb())) {
					return dict.getVal();
				}
			}
		}
		return defaultLb;
	}

	public Map<String, List<Dict>> getAllDictMap() {
		Map<String, List<Dict>> dictMap = new HashMap<String, List<Dict>>();
		List<Dict> allDictList = dictDao.findListBy(null, null);
		for (Dict dict : allDictList) {
			List<Dict> dictList = dictMap.get(dict.getCd());
			if (dictList != null) {
				dictList.add(dict);
			} else {
				dictMap.put(dict.getCd(), Lists.newArrayList(dict));
			}
		}
		return dictMap;
	}

	public List<Dict> getDictListByCd(String cd) {
		Map<String, List<Dict>> allDictMap = getAllDictMap();
		List<Dict> dictList = allDictMap.get(cd);
		if (dictList == null) {
			dictList = Lists.newArrayList();
		}
		return dictList;
	}
	
	public List<Dict> getDictByCd(String cd) {
		Map<String, List<Dict>> allDictMap = dictDao.getDictMap();
		List<Dict> dictList = allDictMap.get(cd);
		if (dictList == null) {
			dictList = Lists.newArrayList();
		}
		return dictList;
	}
}
